package com.tt.utils.wordUtils.renderplicy;

import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.PictureType;
import com.deepoove.poi.data.Pictures;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Title: PoiPictureUtils
 * @Author zl
 * @Package com.oberyun.goHAZOP.utils.wordUtils.renderplicy
 * @Date 2025/9/10 10:02
 * @description: 图片处理工具类
 */

public class PoiPictureUtils {

    private static final Logger logger = LoggerFactory.getLogger(PoiPictureUtils.class);

    // 默认图片大小
    private static final int DEFAULT_WIDTH = 100;
    private static final int DEFAULT_HEIGHT = 100;

    /**
     * 从本地文件创建图片渲染数据
     *
     * @param filePath 图片文件路径
     * @return PictureRenderData
     */
    public static PictureRenderData fromLocalFile(String filePath) {
        return fromLocalFile(filePath, DEFAULT_WIDTH, DEFAULT_HEIGHT);
    }

    /**
     * 从本地文件创建图片渲染数据（指定大小）
     *
     * @param filePath 图片文件路径
     * @param width    图片宽度
     * @param height   图片高度
     * @return PictureRenderData
     */
    public static PictureRenderData fromLocalFile(String filePath, int width, int height) {
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                logger.warn("图片文件不存在: {}", filePath);
                return createPlaceholderImage("文件不存在", width, height);
            }

            // 自动检测图片类型
            String fileName = file.getName().toLowerCase();

            return Pictures.ofLocal(filePath)
                    .size(width, height)
                    .create();
        } catch (Exception e) {
            logger.error("处理本地图片失败: {}", filePath, e);
            return createPlaceholderImage("加载失败", width, height);
        }
    }

    /**
     * 从网络URL创建图片渲染数据
     *
     * @param imageUrl 图片URL地址
     * @return PictureRenderData
     */
    public static PictureRenderData fromNetworkUrl(String imageUrl) {
        return fromNetworkUrl(imageUrl, DEFAULT_WIDTH, DEFAULT_HEIGHT);
    }

    /**
     * 从网络URL创建图片渲染数据（指定大小）
     *
     * @param imageUrl 图片URL地址
     * @param width    图片宽度
     * @param height   图片高度
     * @return PictureRenderData
     */
    public static PictureRenderData fromNetworkUrl(String imageUrl, int width, int height) {
        try {
            // 下载图片并获取字节数组和类型
            ImageData imageData = downloadImageFromUrl(imageUrl);
            if (imageData == null) {
                return createPlaceholderImage("下载失败", width, height);
            }

            return Pictures.ofBytes(imageData.getData(), imageData.getType())
                    .size(width, height)
                    .create();
        } catch (Exception e) {
            logger.error("处理网络图片失败: {}", imageUrl, e);
            return createPlaceholderImage("加载失败", width, height);
        }
    }

    /**
     * 从输入流创建图片渲染数据
     *
     * @param inputStream 图片输入流
     * @param pictureType 图片类型
     * @return PictureRenderData
     */
    public static PictureRenderData fromInputStream(InputStream inputStream, PictureType pictureType) {
        return fromInputStream(inputStream, pictureType, DEFAULT_WIDTH, DEFAULT_HEIGHT);
    }

    /**
     * 从输入流创建图片渲染数据（指定大小）
     *
     * @param inputStream 图片输入流
     * @param pictureType 图片类型
     * @param width       图片宽度
     * @param height      图片高度
     * @return PictureRenderData
     */
    public static PictureRenderData fromInputStream(InputStream inputStream, PictureType pictureType,
                                                    int width, int height) {
        try {
            byte[] imageData = readInputStream(inputStream);
            return Pictures.ofBytes(imageData, pictureType)
                    .size(width, height)
                    .create();
        } catch (Exception e) {
            logger.error("处理输入流图片失败", e);
            return createPlaceholderImage("流处理失败", width, height);
        } finally {
            closeQuietly(inputStream);
        }
    }

    /**
     * 智能创建图片（自动识别来源）
     *
     * @param source 图片来源（文件路径、URL、或输入流）
     * @param type   来源类型（FILE, URL, STREAM）
     * @return PictureRenderData
     */
    public static PictureRenderData createSmartPicture(Object source, PictureSourceType type) {
        return createSmartPicture(source, type, DEFAULT_WIDTH, DEFAULT_HEIGHT, null);
    }

    /**
     * 智能创建图片（自动识别来源，指定大小）
     *
     * @param source      图片来源
     * @param type        来源类型
     * @param width       宽度
     * @param height      高度
     * @param pictureType 图片类型（对于STREAM类型必须指定）
     * @return PictureRenderData
     */
    public static PictureRenderData createSmartPicture(Object source, PictureSourceType type,
                                                       int width, int height, PictureType pictureType) {
        switch (type) {
            case FILE:
                return fromLocalFile((String) source, width, height);
            case URL:
                return fromNetworkUrl((String) source, width, height);
            case STREAM:
                if (pictureType == null) {
                    throw new IllegalArgumentException("输入流类型必须指定pictureType");
                }
                return fromInputStream((InputStream) source, pictureType, width, height);
            default:
                throw new IllegalArgumentException("不支持的图片来源类型: " + type);
        }
    }

    // ============ 私有工具方法 ============

    /**
     * 从URL下载图片
     */
    private static ImageData downloadImageFromUrl(String imageUrl) throws IOException {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        try {
            URL url = new URL(imageUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(10000);

            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                logger.warn("下载图片失败，HTTP状态码: {}", connection.getResponseCode());
                return null;
            }

            // 获取内容类型
            String contentType = connection.getContentType();
            PictureType pictureType = detectPictureTypeFromContentType(contentType);

            inputStream = connection.getInputStream();
            byte[] imageData = readInputStream(inputStream);

            return new ImageData(imageData, pictureType);
        } finally {
            closeQuietly(inputStream);
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    /**
     * 从输入流读取字节数据
     */
    private static byte[] readInputStream(InputStream inputStream) throws IOException {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            return outputStream.toByteArray();
        }
    }

    /**
     * 根据Content-Type检测图片类型
     */
    private static PictureType detectPictureTypeFromContentType(String path) {
        String lower = path.toLowerCase();
        if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) {
            return PictureType.JPEG;
        } else if (lower.endsWith(".png")) {
            return PictureType.PNG;
        } else if (lower.endsWith(".gif")) {
            return PictureType.GIF;
        } else if (lower.endsWith(".bmp")) {
            return PictureType.BMP;
        } else if (lower.endsWith(".wmf")) {
            return PictureType.WMF;
        } else if (lower.endsWith(".emf")) {
            return PictureType.EMF;
        } else if (lower.endsWith(".tiff") || lower.endsWith(".tif")) {
            return PictureType.TIFF;
        }
        return PictureType.PNG;
    }

    /**
     * 创建占位符图片（当图片加载失败时使用）
     */
    private static PictureRenderData createPlaceholderImage(String text, int width, int height) {
        // 这里可以返回一个默认的占位图片
        // 实际项目中可以根据需要实现更复杂的占位逻辑
        // 需要准备一个占位图片
        logger.info("创建占位图片: {}", text);
        return Pictures.ofLocal("path/to/placeholder.png")
                .size(width, height)
                .create();
    }

    /**
     * 安静关闭流
     */
    private static void closeQuietly(InputStream inputStream) {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                logger.warn("关闭输入流失败", e);
            }
        }
    }

    // ============ 内部类和枚举 ============

    /**
     * 图片来源类型枚举
     */
    public enum PictureSourceType {
        FILE,   // 本地文件
        URL,    // 网络URL
        STREAM  // 输入流
    }

    /**
     * 图片数据包装类
     */
    private static class ImageData {
        private byte[] data;
        private PictureType type;

        public ImageData(byte[] data, PictureType type) {
            this.data = data;
            this.type = type;
        }

        public byte[] getData() { return data; }
        public PictureType getType() { return type; }
    }
}
